import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:interview/components/app/app_ripple_button.dart';
import 'package:interview/components/page/page_screen_half.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/controller/interview_tabs_controller.dart';
import 'package:interview/theme/app_colors.dart';

class InterviewTabbar extends StatelessWidget {
  final AppColors theme;
  final int currentIndex;
  final TabController tabController;
  final void Function(int) onTabTapped;

  static final interviewTabsController = Get.find<InterviewTabsController>();

Future<void> onFilterTapped(BuildContext context) async {
  await PageScreenHalf.showHalfScreenModal(
    context,
    dismissible: true,
    showButtons: false,
    content: Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16,),
      child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle("已选择的分类"),
          Obx(() {
            interviewTabsController.tabs.toList(); // 确保 tabs 响应式刷新
            return _buildTabList(
              items: interviewTabsController.tabs,
              isFixedChecker: (tab) => !interviewTabsController.defaultTabs.contains(tab), // 动态判断 isFixed
            );
          }),
          SizedBox(height: 16),
          _buildSectionTitle("可添加分类"),
          Obx(() {
            interviewTabsController.unselectedKeywords.toList(); // 确保关键字响应式刷新
            return _buildTabList(
              items: interviewTabsController.unselectedKeywords,
              isFixedChecker: (_) => false, // 可添加的关键字永远不是固定的
            );
          }),
        ],
      ),
    ),
  );
}

Widget _buildSectionTitle(String title) {
  return Padding(
    padding: EdgeInsets.symmetric(vertical: 12),
    child: Text( title,style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),)
  );
}

Widget _buildTabList({
  required List<String> items,
  required bool Function(String tab) isFixedChecker, // 动态判断 isFixed
}) {
  return Wrap(
    spacing: 12,
    runSpacing: 14,
    children: items.map((tab) {
      return _buildChip(
        tab: tab,
        isFixed:isFixedChecker(tab),
      );
    }).toList(),
  );
}

Widget _buildChip({
  required String tab,
  required bool isFixed,
}) {
  return AppRippleButton(
    backgroundColor: theme.subjectMix2!,
    highlightColor: theme.contrastMix2!.withOpacity(0.2),
    splashColor: theme.contrastMix1!.withOpacity(0.2),
    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 8),
    onTap: () {
      if(interviewTabsController.defaultTabs.contains(tab)) return;
      if (isFixed) {
        interviewTabsController.removeTab(tab);
      } else {
        interviewTabsController.addTab(tab);
      }
    },
    child: Stack(
      clipBehavior: Clip.none, // 防止裁剪图标
      children: [
        _tabItem(tab: tab),
        if(!interviewTabsController.defaultTabs.contains(tab))
          Positioned(
            top: -8, // 调整为更合理的偏移值
            right: -8,
            child: Icon(
              isFixed? CupertinoIcons.clear_circled_solid: CupertinoIcons.add_circled_solid,
              size: 12, // 增大图标尺寸
            ),
          ),
      ],
    ),
  );
}

  const InterviewTabbar({
    super.key, 
    required this.theme, 
    required this.currentIndex, 
    required this.tabController, 
    required this.onTabTapped
  });
  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Expanded(child:
            TabBar(
              controller: tabController,
              isScrollable:true,
              tabAlignment: TabAlignment.start,
              indicatorColor: theme.contrastPure, // 选中状态下划线
              unselectedLabelStyle: TextStyle(
                fontWeight: FontWeight.normal,
                color: theme.contrastMix1,
              ),
              labelStyle: TextStyle(
                fontWeight: FontWeight.bold,
                color: theme.contrastPure,
              ),
              dividerHeight: 0,
              onTap: onTabTapped,
              tabs: interviewTabsController.tabs.map((i){
                return Tab(
                  child :_tabItem(tab: i)
                );
              }).toList()
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(right: 8), // 按钮右侧间距
            child: IconButton(
              icon: Image.asset(
                '${AppEnumAssets.basePath}ic_home_filter.png',
                width: 24,
                height: 24,
              ),
              onPressed:() => onFilterTapped(context) ,
            ),
          ),
        ],
      )
    );
  }



  Widget _tabItem({
    required String tab
  }){
    final iconPath = interviewTabsController.getTabIconPath(tab);
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        SvgPicture.asset( 
          "${AppEnumAssets.basePath}$iconPath" , 
          width: 16 , 
          height: 16,
        ),
        Padding(padding: EdgeInsets.only(left: 6), child:Text(tab , style: TextStyle(fontSize: 12 , fontWeight: FontWeight.w500))),
      ],
    );
  }

}
